<template>
  <view class="user-profile-container mt10">
    <!-- #ifndef  H5 -->
    <u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent">
      <u-navbar
          :is-back="true"
          :title-bold="true"
          :is-fixed="false"
          title="其他"
          title-color="#000000"
          :border-bottom="false"
          back-icon-name="arrow-leftward"
          back-icon-color="#000000"
          :background="{ background: 'rgba(256,256, 256,0)' }"
      ></u-navbar>
    </u-sticky>
    <!-- #endif -->
    <view class="user-profile">
      <view class="row-info row-between  mt10" @click="goToExplain(0)">
        <view class="label nr">注册协议</view>
        <u-icon name="arrow-right"/>
      </view>
      <view class="row-info row-between " @click="goToExplain(1)">
        <view class="label nr">隐私协议</view>
        <u-icon name="arrow-right"/>
      </view>
      <view class="row-info row-between " @click="goToExplain(2)">
        <view class="label nr">责任声明</view>
        <u-icon name="arrow-right"/>
      </view>
      <view class="row-info row-between " @click="goToLogout">
        <view class="label nr"  >注销账号</view>
        <u-icon name="arrow-right"/>
      </view>
      <view class="bg-primary white save-btn row-center lg" @click="logout">退出登录</view>
    </view>


    <u-picker
        mode="selector"
        v-model="showPicker"
        :default-selector="[0]"
        :range="sexList"
        @confirm="onConfirm"
    />
  </view>
</template>

<script>
import {userLogout, getUserInfo, changeUserMobile, setUserInfo, setWechatInfo} from '@/api/user'
import {version} from '@/config/app'
import {sendSms, forgetPwd} from '@/api/app'
import {bindOawechat} from '@/api/user'
import {SMSType} from '@/utils/type'
import {mapState, mapGetters} from 'vuex'
import {uploadFile, isWeixinClient, trottle} from '@/utils/tools'
import {getWxCode, getUserProfile} from '@/utils/login'
import wechath5 from '@/utils/wechath5'

const FieldType = {
  NONE: '',
  SEX: 'sex',
  NICKNAME: 'nickname',
  AVATAR: 'avatar',
  MOBILE: 'mobile'
}
export default {
  name: 'userProfile',
  data() {
    return {
      version: version,
      fileList: [],
      userInfo: {},
      new_mobile: '',
      smsCode: '',
      newNickname: '',
      sexList: ['男', '女'],
      fieldType: FieldType.NONE,
      showPicker: false,
      showMobile: false,
      showPwd: false,
      showNickName: false,
      tips: '',
      canSendSms: true,
      pwd: '',
      comfirmPwd: '',
      smsType: SMSType.FINDPWD,
      code: ''
    }
  },
  methods: {
    oaAuth() {
      wechath5.getWxUrl()
    },
    bindWechat() {
      this.oaAuth()
    },
    handleUser() {
      console.log(123465)
      uni.redirectTo({
        url: '/bundle/pages/user_set/user_set'
      })
    },
    codeChange(text) {
      this.tips = text
    },
    onChooseAvatar(e) {
      this.fieldType = FieldType.AVATAR
      // #ifndef MP-WEIXIN
      // 此为uView的跳转方法，详见"文档-JS"部分，也可以用uni的uni.navigateTo
      uni.$u.route({
        // 关于此路径，请见下方"注意事项"
        url: '/components/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
        // 内部已设置以下默认参数值，可不传这些参数
        params: {
          // 输出图片宽度，高等于宽，单位px
          destWidth: 300,
          // 裁剪框宽度，高等于宽，单位px
          rectWidth: 200,
          // 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
          fileType: 'jpg'
        }
      })
      // #endif
      // #ifdef MP-WEIXIN
      if (e.detail.avatarUrl) {
        console.log(e.detail.avatarUrl)
        this.uploadImage(e.detail.avatarUrl)
      }
      // #endif
    },
    // 修改用户昵称
    async changeNameConfirm(e) {
      this.fieldType = FieldType.NICKNAME
      this.newNickname = e.detail.value.nickname
      if (!this.newNickname)
        return this.$toast({
          title: '请输入新的昵称'
        })
      await this.$setUserInfo(this.newNickname)
      this.showNickName = false
    },

    // end
    logout() {
      //  退出登录
      userLogout({
        token: this.token
      }).then((res) => {
        if (res.code == 1) {
          this.$store.commit('LOGOUT')
          this.$toast({
            title: '退出成功'
          })
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/login/login'
            })
          }, 500)
        }
      })
    },
    goToExplain(value) {
      uni.navigateTo({
        url: '/bundle/pages/server_explan/server_explan?type=' + value
      })
    },
    goLicense() {
      uni.navigateTo({
        url: '/bundle/pages/license/license'
      })
    },
    goToLogout() {
      uni.navigateTo({
        url: '/bundle/pages/user_logout/user_logout'
      })
    },
    toSetPayPwd() {
      if (!this.userInfo.mobile)
        return this.$toast({
          title: '请先设置手机号'
        })
      uni.navigateTo({
        url: '/bundle/pages/set_pay_pwd/set_pay_pwd'
      })
    },
    // 发送短信
    $sendSms(type) {
      if (!this.canSendSms) return
      sendSms({
        mobile: this.userInfo.mobile || this.new_mobile,
        key: this.smsType
      }).then((res) => {
        if (res.code == 1) {
          this.$toast({
            title: res.msg
          })
          this.$refs.uCode.start()
        }
      })
    },
    $getUserInfo() {
      getUserInfo().then((res) => {
        if (res.code == 1) {
          this.userInfo = res.data
        }
      })
    },
    // 更换手机号
    showModifyMobile() {
      this.smsCode = ''
      this.new_mobile = ''
      this.showMobile = true
      this.smsType = this.userInfo.mobile ? SMSType.CHANGE_MOBILE : SMSType.BIND
    },
    $changeUserMobile() {
      if (!this.smsCode) {
        this.$toast({
          title: '请输入验证码'
        })
        return
      }
      if (!this.new_mobile) {
        this.$toast({
          title: '请输入新的手机号码'
        })
        return
      }
      changeUserMobile({
        mobile: this.userInfo.mobile,
        new_mobile: this.new_mobile,
        code: this.smsCode,
        action: this.userInfo.mobile ? 'change' : ''
      }).then((res) => {
        if (res.code == 1) {
          this.showMobile = false
          this.$toast({
            title: res.msg
          })
          this.$getUserInfo()
        }
      })
    },
    // end
    // 修改用户信息
    async $setUserInfo(value) {
      const res = await setUserInfo({
        field: this.fieldType,
        value: value
      })
      if (res.code == 1) {
        this.$toast({
          title: res.msg
        })
        this.$getUserInfo()
      }
    },
    // end
    timeChange(timestamp) {
      console.log(timestamp, 'timestamp')
    },
    onConfirm(value) {
      this.$setUserInfo(value[0] + 1)
      this.showPicker = false
    },
    changeSex(e) {
      this.showPicker = true
      this.fieldType = FieldType.SEX
    },

    // 定时器完成
    countDownFinish() {
      this.canSendSms = true
    },
    // 修改密码
    showPwdPop() {
      if (!this.userInfo.mobile) {
        this.$toast({
          title: '请绑定手机后再设置密码'
        })
        return
      }
      this.smsCode = ''
      this.smsType = SMSType.FINDPWD
      this.showPwd = true
    },
    $forgetPwd() {
      let {smsCode, pwd, comfirmPwd} = this
      if (!smsCode) {
        this.$toast({
          title: '请填写短信验证码'
        })
        return
      }
      if (!pwd) {
        this.$toast({
          title: '请输入新密码'
        })
        return
      }
      if (!comfirmPwd) {
        this.$toast({
          title: '再次输入新密码确认'
        })
        return
      }
      if (pwd != comfirmPwd) {
        this.$toast({
          title: '两次密码输入不一致'
        })
        return
      }
      let data = {
        mobile: this.userInfo.mobile,
        code: smsCode,
        password: pwd,
        repassword: comfirmPwd
      }
      forgetPwd(data).then((res) => {
        if (res.code == 1) {
          this.showPwd = false
          this.$toast({
            title: '设置密码成功'
          })
          this.$getUserInfo()
        }
      })
    },
    // end
    // 修改昵称
    changeName() {
      this.fieldType = FieldType.NICKNAME
      this.newNickname = ''
      this.showNickName = true
    },
    // end

    async getPhoneNumber(e) {
      const {encryptedData, iv} = e.detail
      let data = {
        code: this.code,
        encrypted_data: encryptedData,
        iv
      }
      this.fieldType = FieldType.MOBILE
      if (encryptedData) {
        this.$changeUserMobileMP(data)
      }
    },
    $changeUserMobileMP(data) {
      changeUserMobile(data).then((res) => {
        if (res.code == 1) {
          this.$toast({
            title: res.msg
          })
          this.$getUserInfo()
        }
        // #ifdef MP-WEIXIN
        getWxCode().then((res) => {
          this.code = res
        })
        // #endif
      })
    },
    uploadImage(path) {
      uni.showLoading({
        title: '正在上传中...',
        mask: true
      })
      uploadFile(path)
          .then((res) => {
            uni.hideLoading()
            this.$setUserInfo(res.url)
          })
          .catch(() => {
            uni.hideLoading()
            this.$toast({
              title: '上传失败'
            })
          })
    }
  },
  async onLoad(options) {
    // #ifdef H5

    const bindCode = options.code
    if (bindCode) {
      if (Array.isArray(bindCode)) bindCode = bindCode.pop()

      await bindOawechat({code: bindCode})
    }
    // #endif

    this.$getUserInfo()
    // #ifdef MP-WEIXIN
    getWxCode().then((res) => {
      this.code = res
    })
    // #endif
    // 监听从裁剪页发布的事件，获得裁剪结果
    uni.$on('uAvatarCropper', (path) => {
      console.log(path)
      this.uploadImage(path)
    })
    this.getUserProfile = trottle(this.getUserProfile, 500, this)
  },
  onUnload() {
    uni.$off('uAvatarCropper')
  },
  computed: {
    ...mapState(['token']),
    ...mapGetters(['appConfig'])
  }
}
</script>

<style lang="scss">
page {
  background-image: url("../../static/images/my_bg.jpg");
  background-size: 100%;
  background-repeat: no-repeat;

  .user-profile-container {
    .user-profile {
      margin: 10rpx 20rpx;
      .user-avatar-box {
        padding: 30rpx 20rpx;
        background-color: white;
        border-top-left-radius: 28rpx;
        border-top-right-radius: 28rpx;

        .user-avatar {
          width: 120rpx;
          height: 120rpx;
          border-radius: 50%;
        }
      }

      .row-info {
        margin-bottom: 20rpx;
        padding: 30rpx 20rpx;
        background-color: white;
        border-radius: 16rpx;

        .label {
          width: 180rpx;
          color: #393939;
          font-weight: bold;
        }

        .bd-btn {
          padding: 8rpx 24rpx;
          border: 1px solid $-color-primary;
          color: $-color-primary;
        }
      }

      .license {
        margin-top: 80rpx;
        color: #a7a7a7;
        text-align: center;
      }


      .save-btn {
        margin-top: 40rpx;
        height: 88rpx;
        margin-left: 54rpx;
        margin-right: 54rpx;
        border-radius: 16rpx;
        box-sizing: border-box;
      }

      .updata-btn {
        margin: 0 30rpx;
        margin-top: 40rpx;
        background-color: #0cc267;
      }
    }

    .modify-container {
      padding-left: 30rpx;
      padding-right: 30rpx;
      padding-bottom: 30rpx;
      width: 580rpx;
      border-radius: 30rpx;
      background-color: $-color-white;

      .title {
        padding: 26rpx 0rpx;
      }

      .modify-row {
        padding: 32rpx 0rpx;
        width: 100%;
        border-bottom: 1rpx solid #e5e5e5;

        .send-code-btn {
          border: 1px solid $-color-primary;
          width: 184rpx;
          height: 62rpx;
          color: $-color-primary;
        }
      }

      .btn {
        height: 80rpx;
        padding: 0 180rpx;
        border-radius: 20rpx;
        margin-top: 60rpx;
      }
    }
  }

  .text-name {
    display: flex;
    flex-direction: column;

    justify-content: space-around;
  }
  .bg-primary{
    background-color: #2d6af4;

  }
}
</style>
